import { Component } from '@angular/core';
import { NavParams, ModalController } from '@ionic/angular';
import { VgAPI } from 'videogular2/core';

@Component({
    selector: 'ad-modal',
    templateUrl: './ad-modal.html',
    styleUrls: ['ad-modal.scss']
})
export class ADModal {
    url;
    api: VgAPI;
    timeleft: any = 3;

    constructor(
        params: NavParams, public modalCtrl: ModalController
        ) {
        console.log('url', params.get('url'));
        this.url = params.get('url');
    }

    /**
     * 播放就绪
     * @param api
     */
    onPlayerReady(api: VgAPI) {
        this.api = api;
        this.api.getDefaultMedia().play();
        const timeUpdateSub = this.api.getDefaultMedia().subscriptions.timeUpdate.subscribe((v) => {
            const target = v.currentTarget;
            const currentTime = target.currentTime;
            const duration = target.duration;
            let leftTime = duration - currentTime;
            leftTime = parseInt(leftTime + '', 10);
            if (!this.timeleft || this.timeleft > leftTime) {
                this.timeleft = leftTime;
                if (this.timeleft === 0) {
                    timeUpdateSub.unsubscribe();
                    this.api.getDefaultMedia().currentTime = 0;
                    this.modalCtrl.dismiss();
                }
            }
        });

        // this.api.getDefaultMedia().subscriptions.ended.subscribe(
        //     () => {
        //         timeUpdateSub.unsubscribe();
        //         this.api.getDefaultMedia().currentTime = 0;
        //         // this.timeleft = '';
        //         this.viewCtrl.dismiss();
        //     }
        // );
    }

    /**
     * 关闭广告弹框
     */
    closeModal() {
        this.timeleft = '';
        this.api.getDefaultMedia().currentTime = 0;
        this.modalCtrl.dismiss();
    }


}
